﻿define([
    'dojo/_base/declare',
    'geomap/plugins/layers/KrigingLayer',
    'dojo/dom-construct',
], function (declare, KrigingLayer, DomConstructUtils) {
    var KrigingLayer = declare([KrigingLayer], {
        setData: function (mapView, layer) {
            var options = layer.layer || {};
            this.options = options;
            options.options = options.options || {};
            this.clickEvt = options.onClick;
            var data = $.extend(true, [], options.data);

            this.mapView = mapView;
            var mapUtils = mapView.mapUtils;
            this.mapUtils = mapUtils;

            var lngLatArray = mapUtils.toLngLatArray(mapView, data, options);

            this.world = $.extend(true, [], options.bjGeometry);
            this.valueFieldName = options.valueFieldName || 'z';
            this.clickPointSymbol = options.options.clickPointSymbol || null;

            this.polygonToConvertSr(mapView, this.world, () => {
                this.convertSr(mapView, lngLatArray, () => {
                    this.trainData = this.getData(lngLatArray);

                    this.devicePixelRatio = 1;

                    var colors = Object.assign(
                        {
                            start: '#00ff00',
                            end: '#ff0000',
                            middle: '#ffff00',
                        },
                        options.options.colors
                    );
                    this.gradient = { 0: colors.start, 0.5: colors.middle, 1: colors.end };
                    options.options.gradient = this.gradient;

                    var gradientColor = new mapUtils.GradientColor({
                        startColor: colors.start,
                        endColor: colors.end,
                        step: options.options.step,
                        $threshold: options.options.$threshold,
                        type: options.options.gradientColorType,
                    });

                    this.colors = gradientColor;
                    this._draw();
                    if (Object.prototype.toString.call(options.callback) == '[object Function]') {
                        options.callback(layer);
                    }
                });
            });

            if (options.options.isShowLegend) {
                this.getLegend(options.options.legendOptions);
            }
        },

        getData(data) {
            var obj = {};
            data.__proto__ = Array.prototype;
            var i,
                n = data.length;
            obj.t = Array(n);
            obj.x = Array(n);
            obj.y = Array(n);
            var valueFieldName = this.valueFieldName;

            for (i = 0; i < n; i++) {
                obj.t[i] = data[i][valueFieldName];
                obj.x[i] = data[i].x;
                obj.y[i] = data[i].y;
            }
            return obj;
        },
        getLocation: function () {
            var esriEvent = this._esriEvent;
            var location = this.getGraphicLocation(this.mapView, esriEvent);
            location.event = esriEvent;
            return location;
        },
        getGraphicLocation: function (mapView, esriEvent) {
            if (!esriEvent || !esriEvent.graphic) {
                return;
            }
            if (!mapView) {
                return;
            }
            var map = mapView.getMap();
            if (!map) {
                return;
            }
            var geometry = esriEvent.graphic.geometry || {};
            var lngFieldName = mapView.getLngFieldName();
            var latFieldName = mapView.getLatFieldName();
            var location = {};
            location[lngFieldName] = geometry.x;
            location[latFieldName] = geometry.y;
            return location;
        },
        getLegend: function (options = {}) {
            var gradient = this.gradient;
            var canvasHeight = parseInt(options.canvasHeight) || 120;
            var canvasWidth = parseInt(options.canvasWidth) || 20;
            this._legendElement = DomConstructUtils.create(
                'div',
                {
                    style: Object.assign({}, options.style),
                    class: ['layerLegend'],
                },
                this.layersElement
            );

            var titleElement = DomConstructUtils.create(
                'div',
                {
                    style: {
                        'text-align': 'center',
                        'font-size': '16px',
                        'font-weight': 'bold',
                    },
                },
                this._legendElement
            );
            titleElement.innerHTML = `<div style="padding-bottom:5px;">图&nbsp&nbsp例</div>`;
            var contentElement = DomConstructUtils.create(
                'div',
                { style: { position: 'relative' } },
                this._legendElement
            );
            contentElement.innerHTML = `<div style="position:absolute;top: -2px;right: 0px;">最大值</div>
                                      <div style="position:absolute;top: ${
                                          canvasHeight - 16
                                      }px;right: 0px;">最小值</div>
                                     `;
            var _contentWidth = $(contentElement).width() || 42;
            var canvas = DomConstructUtils.create(
                'canvas',
                {
                    width: canvasWidth + _contentWidth + 'px',
                    height: canvasHeight + 'px',
                },
                contentElement
            );

            var paletteCtx = canvas.getContext('2d');

            var lineGradient = paletteCtx.createLinearGradient(0, canvasHeight, 0, 0);
            for (var key in gradient) {
                lineGradient.addColorStop(parseFloat(key), gradient[key]);
            }
            paletteCtx.fillStyle = lineGradient;
            paletteCtx.fillRect(0, 0, canvasWidth, canvasHeight);

            return canvas;
        },
        polygonToConvertSr(mapView, data, callback) {
            var me = this;
            var mapSr = mapView.getSpatialReference();
            me.mapSr = mapSr;
            var layerSr = me.spatialReference;
            if (mapSr == layerSr) {
                callback();
                return;
            }
            var index = 0;
            for (let i = 0; i < data.length; i++) {
                let points = [];
                for (let j = 0; j < data[i].length; j++) {
                    points.push({
                        x: data[i][j][0],
                        y: data[i][j][1],
                    });
                }
                me.convertSr(mapView, points, function (lngLatArray) {
                    lngLatArray.map(function (item, ix) {
                        data[i][ix] = [item.x, item.y];
                    });
                    if (index == data.length - 1) {
                        callback.call(me);
                    }
                    index++;
                });
            }
        },
        convertSr: function (mapView, lngLatArray, callback) {
            var me = this;
            if (!mapView) {
                return;
            }
            var mapUtils = mapView.mapUtils;
            var mapSr = mapView.getSpatialReference();
            me.mapSr = mapSr;
            var layerSr = me.spatialReference;
            if (mapSr == layerSr) {
                callback();
                return;
            }
            /*坐标转换，扩展的图层不像svg可以自动转换坐标，如果点位的坐标与底图的坐标不一致需要先手工转换坐标*/
            if (mapSr.wkid == '102100') {
                if (layerSr.wkid == '4326' || layerSr.wkid == '4490') {
                    me.lngLatToXY(mapView, lngLatArray, function (lngLatArray) {
                        if ($.isFunction(callback)) {
                            callback(lngLatArray, mapSr);
                        }
                    });
                    return;
                }
            }
            if (mapSr.wkid == '4326' || mapSr.wkid == '4490') {
                if (layerSr.wkid == '102100') {
                    me.xyToLngLat(mapView, lngLatArray, function (lngLatArray) {
                        if ($.isFunction(callback)) {
                            callback(lngLatArray, mapSr);
                        }
                    });
                    return;
                }
            }
            if ($.isFunction(callback)) {
                callback(lngLatArray, me.spatialReference);
            }
        },
        lngLatToXY: function (mapView, lngLatArray, callback) {
            mapView.mapUtils.webMercatorUtils(mapView, lngLatArray, {
                isLngLat: true,
                callback: callback,
            });
        },
        xyToLngLat: function (mapView, data, callback) {
            mapView.mapUtils.webMercatorUtils(mapView, lngLatArray, {
                isLngLat: false,
                callback: callback,
            });
        },
    });
    return KrigingLayer;
});
